<?php


namespace app\api\model;


use app\api\community\utils\basicUtils;
use think\Model;

class shortChainModel extends Model
{

    protected $table = 'short_chain_table';

    /**
     * 保存url
     * @param string $url
     * @return string
     * @throws \Exception
     */
    public function saveShortUrl(string $url): string
    {
        $url = trim($url);
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            return 'URL format verification error';
        }

        $shortUrl = (new basicUtils()) -> shortUrl($url);

        // 验证当前链接是否存在
        if ($this->getShortUrl($shortUrl) === '暂无链接') {
            $urlSuccess = httpRequest($url) -> getData();
            if (!$urlSuccess)return 'URL ResponseBody is Empty or Url Pages does not exists';
            self::create([
                'short_code' => $shortUrl,
                'url' => $url
            ]);
        }
        return  request() -> host() . '/' . $shortUrl;
    }

    /**
     * 获取url
     * @param string $url
     * @return string
     */
    public function getShortUrl(string $url): string
    {
        $url = $this->where([
            'short_code' => $url
        ]) -> findOrEmpty();

        if ($url -> isExists()) {
            return $url['url'];
        }
        return '暂无链接';
    }

}